/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.facade.employment;

import com.xtd.model.employment.Employee;
import com.xtd.model.employment.Payroll;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.EntityManager;

/**
 *
 * @author Lu Yuanbin
 */
public abstract class PayrollCalculator {

    abstract public Payroll calculatePayroll(EntityManager em, Employee employee, Date startDate, Date endDate, Employee createdBy);

    public BigDecimal calculateIntrudoctionRoyalty(EntityManager em, Employee employee, Date startDate, Date endDate) {
        BigDecimal royalty1 = (BigDecimal) em.createQuery("select sum(((os.orderCommodity.quantity-os.orderCommodity.returnedQuantity)* os.orderCommodity.unitPrice)*os.introducerRoyalty)"
                + " from OrderServer as os where"
                + " os.orderCommodity.shootingOrder is not null and os.orderCommodity.shootingOrder.introducer = :employee and os.settledTime between :startDate and :endDate").setParameter("employee", employee).setParameter("startDate", startDate).setParameter("endDate", endDate).getSingleResult();
        if (royalty1 == null) {
            royalty1 = BigDecimal.ZERO;
        }

        BigDecimal royalty2 = (BigDecimal) em.createQuery("select sum((os.orderCommodity.quantity-os.orderCommodity.returnedQuantity) * os.quantityRoyalty + ((os.orderCommodity.quantity-os.orderCommodity.returnedQuantity)* os.orderCommodity.unitPrice)*(os.priceRoyalty-os.introducerRoyalty))"
                + " from OrderServer as os where os.server = :employee  and "
                + " os.orderCommodity.superOrderCommodity is not null  and os.settledTime between :startDate and :endDate").setParameter("employee", employee).setParameter("startDate", startDate).setParameter("endDate", endDate).getSingleResult();

        if (royalty2 == null) {
            royalty2 = BigDecimal.ZERO;
        }

        return royalty1.add(royalty2);
    }
}
